#include "mem_utils.h"

/**
 * This function will copy memory content from source address to destination
 * address. This version handles memory overlap safely.
 *
 * @param dst the address of destination memory
 * @param src the address of source memory  
 * @param count the copied length
 *
 * @return the address of destination memory
 */
void *mymemcpy(void *dst, const void *src, unsigned int len)
{
	char *xdst = (char *)dst;	
	const char *xsrc = (const char *)src;
	
	if(xdst > xsrc && xdst < xsrc + len)
	{
		for(unsigned int i = len; i > 0; i--)
		{
			xdst[i-1] = xsrc[i-1];
		}
	}
	else
	{
		for(unsigned int i = 0; i < len; i++)
		{
			xdst[i] = xsrc[i];
		}
	}
	
	return dst;
}

/**
 * This function will compare two areas of memory
 *
 * @param cmp1 one area of memory
 * @param cmp2 another area of memory
 * @param count the size of the area
 *
 * @return the result: 0 if equal, positive if cmp1 > cmp2, negative if cmp1 < cmp2
 */
int mymemcmp(const void *cmp1, const void *cmp2, unsigned int len)
{
	const unsigned char *temp_cmp1, *temp_cmp2;

	int res = 0;
	for(temp_cmp1 = (const unsigned char *)cmp1, temp_cmp2 = (const unsigned char *)cmp2;
			len > 0; temp_cmp1++, temp_cmp2++, len--)
		if((res = *temp_cmp1 - *temp_cmp2) != 0)
			break;
		
	return res;
}



